const express = require('express')
const router = express.Router()
const mysql = require('mysql')
//  建立 与 mysql 数据库的链接 
const db = mysql.createPool({
    host: '127.0.0.1',  //  数据库 ip 地址
    port: 3306,          //   端口号   
    user: 'root',      //   登录数据库的账号
    password: 'admin123',   // 登录数据库的密码
    database: "new_mydb01"  //  指定要操作的数据库
})
const newPool = async (sqlStr, params) => {
    const p = new Promise((reslove, reject) => {
        db.query(sqlStr, params, (err, result) => {
            if (err) return reject(err)
            reslove(result)
        })
    })
    const res = await p
    return res
}
router.get('/getUsers', async (req, res) => {
    const status = req.query.status
    const queryStr = 'select * from users where isDelete!=1 and status=?'
    const result = await newPool(queryStr, status)
    console.log(result)
    if (result.length > 0) {
        res.status(200).json({
            code: 200,
            data: result,
            msg: '查询成功'
        })
    } else {
        res.status(200).json({
            code: 200,
            data: null,
            msg: '查询成功'
        })
    }
})
// 查询分页参数
router.get('/getUserPage', async (req, res) => {
    const pageSize = req.query.pageSize || 5
    const page = req.query.page || 1
    const status = req.query.status
    const queryStr = 'select * from users where isDelete!=1  limit ?,? '
    console.log('12131212', [(page - 1) * pageSize, page * pageSize])
    const result = await newPool(queryStr, [(page - 1) * pageSize, +pageSize])
    console.log(result.length)
    if (result.length > 0) {
        res.status(200).json({
            code: 200,
            data: result,
            msg: '查询成功'
        })
    } else {
        res.status(200).json({
            code: 200,
            data: null,
            msg: '查询成功'
        })
    }
})

module.exports = router